package com.eipc.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.json.JSONObject;

import com.eipc.UpdateProgressActivity;
import com.eipc.info.R;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.util.Log;
import android.webkit.URLUtil;


public class UpdateManager {
	public static int len  = 1;
	public static int cLen = 1;
	public static int currentVersion = 69;
	public boolean beginUpload = false;
	private static String strURL_APK= "";
	private Context mContent;
	private int serVersion;
	private AlertDialog.Builder mBuilder;
	
	// 更新
	public void Update(Context c){
		
//		mBuilder = new Builder(this).setTitle(R.string.tip);
		mContent = c;
		// 检验当前版本与服务器最新版本
		Log.e("----------update-----------","----begin check version----");
		if (checkUpdate()){
			Log.e("----------update-----------","----begin update----");
			// 获取文件
			// 进度条提示文件下载中
			if(!beginUpload){
				this.getFile(strURL_APK);
			}
			
			// delete
		}
		else
		{
			mBuilder = new Builder(mContent).setTitle(R.string.tip);
			
			mBuilder.setMessage(R.string.do_not_need_update)
			.setNegativeButton(R.string.btn_close, null)
			.show();
			
//	         new AlertDialog.Builder(mContent)
//	         .setMessage(R.string.do_not_need_update)
//	         .setTitle("对话框").setNegativeButton(R.string.btn_close, null).show();
	         
			
			
		}
	}
	
	private boolean checkUpdate(){
		boolean needUpdate = false;
		int curVersion = currentVersion;
//		curVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode);
		try {
			curVersion = mContent.getPackageManager().getPackageInfo(mContent.getPackageName(),0).versionCode;
			Log.e("----------update-----------","----curVersion----"+curVersion);
		} catch (NameNotFoundException e) {
		}		
		serVersion = GetURL_VersionCode();
		//if (curVersion < serVersion && currentVersion < serVersion){
		if (curVersion < serVersion){
			needUpdate = true;
		}
		
		return needUpdate;		
	}
	
	private int GetURL_VersionCode(){
		int iVersionCode = currentVersion;
		try {
			JSONObject j = new JSONObject(HttpManager.push("http://124.74.67.130:8080/Atp/version/version.action",false,null));
			iVersionCode = Integer.valueOf(j.getString("version"));
			String url = j.getString("url");
			strURL_APK = "http://124.74.67.130:8080/Atp/"+url;
		} catch (Exception e) {
			e.printStackTrace();
		}
		Log.e("----------update-----------","----service Version----" + iVersionCode);
		return iVersionCode;		
	}
		
	private void getDataSource(String strPath) throws Exception 
	  { 
	    if (!URLUtil.isNetworkUrl(strPath)) 
	    { 
	    	Log.e("----------update-----------","----strURL_APK ERROR----" ); 
	    } 
	    else 
	    { 
	        URL myURL = new URL(strPath); 
	        URLConnection conn = myURL.openConnection();   
	        conn.connect();   
	        
	        InputStream is = conn.getInputStream();   
	        if (is == null) 
	        { 
	          throw new RuntimeException("stream is null"); 
	        } 
	        
	        String fileEx = strPath.substring(strPath.lastIndexOf(".")+1,strPath.length()).toLowerCase();
	        String fileNa = strPath.substring(strPath.lastIndexOf("/")+1,strPath.lastIndexOf("."));
	        
	        File myTempFile = File.createTempFile(fileNa, "."+fileEx); 	        
//	        String currentTempFilePath = myTempFile.getAbsolutePath(); 
	         
	        FileOutputStream fos = new FileOutputStream(myTempFile); 
	        len = conn.getContentLength();
	        cLen = 0;
	        byte buf[] = new byte[128];   
	        Log.e("----------update-----------","----begin load file----" ); 
	        do 
	        {   
	          int numread = is.read(buf);   
	          if (numread <= 0) 
	          { 
	            break; 
	          } 
	          fos.write(buf, 0, numread);  
	          cLen += numread;
	          //Log.e("----------update-----------",cLen+"/"+len); 
	        }while (true);  
	        	        
	        openFile(myTempFile);
	        
	        try 
	        { 
	          is.close(); 
	        } 
	        catch (Exception ex) 
	        { 
	          // TODO 
	        } 
	      }
	    }  
	
	private void openFile(File f){
		Log.e("----------update-----------","----begin install ----" ); 
		currentVersion = serVersion;
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		String type = getMIMEType(f);
		Log.e("----------update-----------","----MIMEType ----" +type); 
		intent.setDataAndType(Uri.fromFile(f),type);
		mContent.startActivity(intent);
	}
	
	private void delFile(String strFileName) 
	  { 
	    File myFile = new File(strFileName); 
	    if(myFile.exists()) 
	    { 
	      myFile.delete(); 
	    } 
	  } 
	 	
	private String getMIMEType(File f) 
	{
		String type="";
	    String fName=f.getName();	    
	    String end=fName.substring(fName.lastIndexOf(".")+1,fName.length()).toLowerCase();
	    	    
	    if(end.equals("m4a")||end.equals("mp3")||end.equals("mid")||end.equals("xmf")||end.equals("ogg")||end.equals("wav"))
	    {
	      type = "audio"; 
	    }
	    else if(end.equals("3gp")||end.equals("mp4"))
	    {
	      type = "video";
	    }
	    else if(end.equals("jpg")||end.equals("gif")||end.equals("png")||end.equals("jpeg")||end.equals("bmp"))
	    {
	      type = "image";
	    }
	    else if(end.equals("apk")) 
	    { 
	      /* android.permission.INSTALL_PACKAGES */ 
	      type = "application/vnd.android.package-archive"; 
	    } 
	    else
	    {
	      type="*";
	    }
	    
	    if(end.equals("apk")) 
	    { 
	    } 
	    else 
	    { 
	      type += "/*";  
	    } 
	    return type;		 
	}	  
	
	private void getFile(final String strPath) 
	{
		try 
	    {
			Runnable r = new Runnable()
			{
				public void run()
				{
					try
					{  
						beginUpload = true;
						synchronized (UpdateManager.class){
							getDataSource(strPath);
							
						}
					}
					catch (Exception e)
					{
						// TODO
					}
				} 
			};
			new Thread(r).start();
			Intent i = new Intent(mContent, UpdateProgressActivity.class);
			mContent.startActivity(i);
		} 
	    catch(Exception e) 
	    {	    	
	    	e.printStackTrace(); 
	    }
	  } 

 }

